<?php
namespace App\Services\Trade\Auth;

use Illuminate\Support\Facades\DB;
use App\Mappers\Trade\ShopMapper;
use App\Models\Base\UserModel;
use App\Models\Base\DistrictModel;
use App\Models\Trade\Shop\ShopModel;
use App\Models\Trade\Shop\ShopCountModel;
use App\Models\Trade\Shop\ShopCollectionModel;
use App\Exceptions\Response\Service\ServiceException;
use App\Exceptions\Response\Service\ServiceCode;

class ShopService
{

    /**
     * 保存数据
     *
     * @param \Illuminate\Http\Request $request
     * @param int $userId
     * @throws ServiceException
     * @return id
     */
    public function saveItem($request, $userId)
    {
        // 数据映射
        $shopMapper = new ShopMapper($request->all());
        $shopData = $shopMapper->make()->toArray();
        // 店铺
        $shop = ShopModel::findByUserId($userId, ['id'])->shift();
        // 更新
        if ($shop && ! ($number = ShopModel::editItem($shop['id'], $shopData))) {
            throw new ServiceException(ServiceCode::SERVICE_ACTION_SAVE_ERROR);
        }
        // 创建
        if (! $shop) {
            $shopData['user_id'] = $userId;
            if (! ($shop['id'] = ShopModel::addItem($shopData))) {
                throw new ServiceException(ServiceCode::SERVICE_ACTION_SAVE_ERROR);
            }
        }
        return $shop['id'];
    }

    /**
     * 关注店铺/取消关注
     *
     * @param int $id
     * @param int $type
     * @param int $userId
     * @throws ServiceException
     * @return boolean
     */
    public function collectionItem($id, $type, $userId)
    {
        // 存在检查
        if ($type == ShopCollectionModel::ACTION_TYPE_DEFAULT && ShopCollectionModel::findItem($userId, $id)->count()) {
            throw new ServiceException(ServiceCode::SERVICE_DATA_EXISTED);
        }
        // 关注店铺
        if ($type == ShopCollectionModel::ACTION_TYPE_DEFAULT && ! ($number = ShopCollectionModel::addItem($userId, $id))) {
            throw new ServiceException(ServiceCode::SERVICE_ACTION_SAVE_ERROR);
        }
        // 不存在检查
        if ($type == ShopCollectionModel::ACTION_TYPE_DELETE && ! ShopCollectionModel::findItem($userId, $id)->count()) {
            throw new ServiceException(ServiceCode::SERVICE_DATA_NOT_EXIST);
        }
        // 取消关注
        if ($type == ShopCollectionModel::ACTION_TYPE_DELETE && ! ($number = ShopCollectionModel::banItem($userId, $id))) {
            throw new ServiceException(ServiceCode::SERVICE_ACTION_SAVE_ERROR);
        }

        // 抛出关注事件
        \App\Events\Trade\Shop\CollectionEvent::dispatch($id, $type);
        
        return (boolean) $number;
    }

    /**
     * 批量删除关注
     *
     * @param array $ids
     * @param int $userId
     * @throws ServiceException
     * @return boolean
     */
    public function deleteCollection($ids, $userId)
    {
        // 统计批量自减
        if (! ($number = ShopCountModel::decCollectionByShopIds($ids, $userId))) {
            throw new ServiceException(ServiceCode::SERVICE_ACTION_SAVE_ERROR);
        }
        // 关注批量删除
        if (! ($number = ShopCollectionModel::banList($userId, $ids))) {
            throw new ServiceException(ServiceCode::SERVICE_ACTION_SAVE_ERROR);
        }
    
        return (boolean) $number;
    }
    
    /**
     * 获取查询字段（列表）
     * 
     * @return string
     */
    protected function makeFieldList()
    {
        return implode(',', [
            'd.id,d.user_id,d.verify_classify,d.verify_name,d.verify_type',
            'd.contact_name,d.kind_supply,d.kind_demand,d.created,d.updated,d.status',
            'd.province,p.name as province_name,d.city,c.name as city_name,u.avatar'
        ]);
    }
    
    /**
     * 获取收藏列表
     *
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @param int $userId
     * @return array(\Illuminate\Support\Collection, int)
     */
    public function selectCollectionList($page, $pageSize, $userId)
    {
        $queryList = ShopCollectionModel::dbTable('dd');
        $queryCount = clone $queryList;

        $where[] = ['dd.user_id', $userId];

        // 查询数量
        $count = $queryCount->where($where)->count();
        // 查询数据
        $collection = $queryList->select(DB::raw($this->makeFieldList()))
            ->leftJoin(ShopModel::TABLENAME . ' as d', 'd.id', '=', 'dd.shop_id')
            ->leftJoin(DistrictModel::TABLENAME . ' as p', 'p.id', '=', 'd.province')
            ->leftJoin(DistrictModel::TABLENAME . ' as c', 'c.id', '=', 'd.city')
            ->leftJoin(UserModel::TABLENAME . ' as u', 'u.id', '=', 'd.user_id')
            ->where($where)
            ->orderBy('dd.created', 'desc')
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get();
        
        return array(
            $collection,
            $count
        );
    }
}